package com.netjava.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.netjava.dao.IProductDAO;
import com.netjava.pojo.Product;

/**
 * A data access object (DAO) providing persistence and search support for
 * Product entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.netjava.pojo.Product
 * @author MyEclipse Persistence Tools
 */

public class ProductDAO extends HibernateDaoSupport implements IProductDAO {
	private static final Log log = LogFactory.getLog(ProductDAO.class);
	// property constants
	public static final String PRODUCT_NAME = "productName";
	public static final String BASE_PRICE = "basePrice";
	public static final String MARKET_PRICE = "marketPrice";
	public static final String STATE = "state";
	public static final String DETAILS = "details";
	public static final String IMAGE1 = "image1";
	public static final String IMAGE2 = "image2";
	public static final String IMAGE3 = "image3";
	public static final String OTHER1 = "other1";
	public static final String OTHER2 = "other2";

	protected void initDao() {
		// do nothing
	}

	public Product save(Product product) {
		log.debug("saving Product instance");
		try {
			getHibernateTemplate().save(product);
			log.debug("save successful");
			return product;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Product product) {
		log.debug("deleting Product instance");
		try {
			getHibernateTemplate().delete(product);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	


	public Product findById(java.lang.Integer id) {
		log.debug("getting Product instance with id: " + id);
		try {
			Product instance = (Product) getHibernateTemplate().get(
					"com.netjava.pojo.Product", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Product instance) {
		log.debug("finding Product instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Product instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Product as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByProductName(Object productName) {
		return findByProperty(PRODUCT_NAME, productName);
	}

	public List findByBasePrice(Object basePrice) {
		return findByProperty(BASE_PRICE, basePrice);
	}

	public List findByMarketPrice(Object marketPrice) {
		return findByProperty(MARKET_PRICE, marketPrice);
	}

	public List findByState(Object state) {
		return findByProperty(STATE, state);
	}

	public List findByDetails(Object details) {
		return findByProperty(DETAILS, details);
	}

	public List findByImage1(Object image1) {
		return findByProperty(IMAGE1, image1);
	}

	public List findByImage2(Object image2) {
		return findByProperty(IMAGE2, image2);
	}

	public List findByImage3(Object image3) {
		return findByProperty(IMAGE3, image3);
	}

	public List findByOther1(Object other1) {
		return findByProperty(OTHER1, other1);
	}

	public List findByOther2(Object other2) {
		return findByProperty(OTHER2, other2);
	}

	public List findAll() {
		log.debug("finding all Product instances");
		try {
			String queryString = "from Product";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
/**
 * 如果session中有一个和detachedInstance的identify相同的对象，合并两个对象，或者保存新对象到数据库
 * @param detachedInstance：托管的对象，没有和session关联
 * @return
 */
	public Product merge(Product detachedInstance) {
		log.debug("merging Product instance");
		try {
			Product result = (Product) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Product instance) {
		log.debug("attaching dirty Product instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Product instance) {
		log.debug("attaching clean Product instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	/**
	 * 根据状态进行分页查询
	 * @param state：商品状态。
	 * @return
	 */
    @SuppressWarnings("unchecked")
	public List<Product> pageCutSel(final Integer state,final Integer page,final Integer num){
    	List<Product> list=(List<Product>)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String queryString="FROM com.netjava.pojo.Product AS product WHERE product.state=?";
				Query query=session.createQuery(queryString);
				query.setInteger(0, state);
				query.setFirstResult((page-1)*num);
				query.setMaxResults(10);
				return query.list();
			}
    		
    	});
    	return list;
    }
	public static ProductDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ProductDAO) ctx.getBean("ProductDAO");
	}
}